package com.example.administrator.myapplication;

import android.Manifest;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ManageMediaActivity extends AppCompatActivity {
    private final int PERMISSION_REQUEST_CODE = 1;
    Button addMediaBnt;
    Button viewMediaBnt;
    ListView mediaList;
    ArrayList<String> ids = new ArrayList<>();
    ArrayList<String> fileNames = new ArrayList<>();
    ArrayList<String> imageData = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manage_media);
        addMediaBnt = (Button) findViewById(R.id.addMediaBnt);
        viewMediaBnt = (Button) findViewById(R.id.viewMediaBnt);
        mediaList = (ListView) findViewById(R.id.mediaList);
        viewMediaBnt.setOnClickListener(new ViewMediaOnClickListener());
        addMediaBnt.setOnClickListener(new AddMediaOnClickListener());
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                    ManageMediaActivity.this, new String[]{
                            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    PERMISSION_REQUEST_CODE);
                    }
                    else{
            viewMediaBnt.setEnabled(true);
            addMediaBnt.setEnabled(true);
        }
    }
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        switch(requestCode){
            case PERMISSION_REQUEST_CODE:
                if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    viewMediaBnt.setEnabled(true);
                    addMediaBnt.setEnabled(true);
                }
        else{
                    Toast.makeText(this, "你没有同意授权", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    private class AddMediaOnClickListener implements View.OnClickListener {
        public void onClick(View view) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DISPLAY_NAME, "belltower");
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            Bitmap bitmap = BitmapFactory.decodeResource(
                    ManageMediaActivity.this.getResources(), R.drawable.belltower);
            OutputStream os = null;
            try {
                os = getContentResolver().openOutputStream(uri);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
                os.close();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    private class ViewMediaOnClickListener implements View.OnClickListener {
        public void onClick(View view) {
            ids.clear();
            fileNames.clear();
            imageData.clear();
            Cursor cursor = getContentResolver().query(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
            while (cursor.moveToNext()) {
                String id = cursor.getString((int) cursor.getColumnIndex(MediaStore.Images.Media._ID));
                String title = cursor.getString((int) cursor.getColumnIndex(MediaStore.Images.Media.TITLE));
                byte[] data = cursor.getBlob((int) cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                ids.add(id);
                fileNames.add(title);
                imageData.add(new String(data, 0, data.length - 1));
            }
            cursor.close();
            List<Map<String, Object>> listItems = new ArrayList<>();
            for (int i = 0; i < ids.size(); i++) {
                Map<String, Object> listItem = new HashMap<>();
                listItem.put("id", ids.get(i));
                listItem.put("title", fileNames.get(i) + ".jpg");
                listItems.add(listItem);
            }
            SimpleAdapter simpleAdapter = new SimpleAdapter(
                    ManageMediaActivity.this, listItems, R.layout.line,
                    new String[]{"id", "title"},
                    new int[]{R.id.pic_id, R.id.title});
            mediaList.setAdapter(simpleAdapter);
            mediaList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View source, int position, long id) {
                    View viewDialog = getLayoutInflater().inflate(R.layout.view, null);
                    ImageView image = (ImageView) viewDialog.findViewById(R.id.image);
                    image.setImageBitmap(BitmapFactory.decodeFile(imageData.get(position)));
                    new AlertDialog.Builder(ManageMediaActivity.this). setView(viewDialog). setPositiveButton("确定", null).show();
                }
            });
        }
    }
}



